package org.bookie.framework.components;

import java.util.Date;

import org.apache.commons.lang.time.DurationFormatUtils;
import org.apache.tapestry.AbstractComponent;
import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IRequestCycle;

/**
 * Formats the time gap as a string and writes it into the HTML.
 * The gap is the difference between now and the specified date.
 * <p>
 * The following examples demonstrates all possible outputs:
 * <ul>
 * <li>2 days 14 hours 2 minutes 13 seconds</li>
 * <li>5 hours 39 minutes 25 seconds</li>
 * <li>17 minutes 48 seconds</li>
 * <li>9 seconds</li>
 * </ul>
 * 
 * @author Igor Drobiazko
 *
 */
public abstract class DownCounter extends AbstractComponent {
	@Override
	protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle) {
		if (getValue() == null) {
			return;
		}
		long diff = getValue().getTime() - System.currentTimeMillis();
		writer.print(DurationFormatUtils.formatDuration(diff, getFormat()));
	}
	
	private String getFormat(){
		StringBuffer format = new StringBuffer();
		format.append("d' ");
		format.append(getMessages().getMessage("days"));
		format.append(" 'H' ");
		format.append(getMessages().getMessage("hours"));
		format.append(" 'm' ");
		format.append(getMessages().getMessage("minutes"));
		format.append(" 's' ");
		format.append(getMessages().getMessage("seconds"));
		format.append("'");
		return format.toString();
	}
	
	public abstract Date getValue();

}
